package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.StaticData;
import com.mp.approvalreq.service.ReadTemplateServicePrx;
import com.mp.approvalreq.util.ServiceUtils;
import com.plusmoney.exception.RpcServerLogicalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 获得统计数据
 *
 * @author Administrator
 */
@WebServlet("/ooooooooookkkkkkkkkkk")
public class GetStaticData extends AbstractServlet {

	private static final long serialVersionUID = -6524473373623928868L;

	private static final Logger logger = LoggerFactory.getLogger(GetStaticData.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	/**
	 * [contactId,contactId,contactId,contactId]
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			List<Integer> list = getIntegers(req);

			ReadTemplateServicePrx readTemplateServicePrx = ServiceUtils.getReadTemplateServicePrx();
			List<StaticData> staticDatas = readTemplateServicePrx.getStaticData(list);

			returnResult(resp, staticDatas);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}

	private List<Integer> getIntegers(HttpServletRequest req) throws IOException {
		String reqBody = getContent(req);
		logger.info("json参数 {}", reqBody);

		List<Integer> list = null;
		try {
			list = JSONArray.parseArray(reqBody, Integer.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
		}

		if (list == null || list.size() < 1) {
			throw new RpcServerLogicalException(1, "无输入参数");
		}

		return list;
	}

	private void returnResult(HttpServletResponse resp, List<StaticData> staticDatas) throws IOException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "0");
		jsonObject.put("res_info", "获得成功");
		jsonObject.put("item", staticDatas);

		logger.info(jsonObject.toJSONString());

		printJson(resp, jsonObject.toJSONString());
	}

}
